
from tools.enum_define import ENUMURLCODE
from tools.utils import code2openid
from db.querydb import request_db_param

# 用户注册
def usrRegister(dict_data):
    '''
    code - 用户唯一id
    area - 小区编号
    deviceid - 设备编号
    passwd - 密码
    '''
    #TODO 
    result = dict()
    area = dict_data.get('area')
    deviceid = dict_data.get('deviceid')
    code = dict_data.get('code')
    print('code is ', code)
    passwd = dict_data.get('passwd')
    if ( code is None or area is None or deviceid is None or passwd is None):
        result['errcode'] = ENUMURLCODE.db_datafield_miss.value
        result['errmsg'] = 'missing params'
        return result
    openid = code2openid(code)
    if (openid is None):
        result['errcode'] = ENUMURLCODE.login_no_openid.value
        result['errmsg'] = 'wechat token failed'
        return result
    
    params = dict()
    params['openid'] = openid
    params['area'] = area
    params['deviceid'] = deviceid
    params['passwd'] = passwd
    ret = request_db_param('nn_userRegister', params)
    #print('errcode is ', ret[0])
    #print('errmsg is', ret[1])
    #result['errcode'] = ret[0]
    #result['errmsg'] = ret[1]
    return ret[1]

# 权限验证
def usrCerCheck(dict_data):
    #TODO
    result = dict()
    area = dict_data.get('area')
    deviceid = dict_data.get('deviceid')
    code = dict_data.get('code')
    if ( code is None or area is None or deviceid is None):
        result['errcode'] = ENUMURLCODE.db_datafield_miss.value
        result['errmsg'] = 'missing params'
        return result
    openid = code2openid(code)
    if (openid is None):
        result['errcode'] = ENUMURLCODE.login_no_openid.value
        result['errmsg'] = 'wechat token failed'
        return result, openid
    
    params = dict()
    params['openid'] = openid
    params['area'] = area
    params['deviceid'] = deviceid
    ret = request_db_param('nn_userCheck', params)
    #result['errcode'] = ret[0]
    #result['errmsg'] = ret[1]
    return ret[1], openid

